package edu.zut.summer.rest;


import edu.zut.summer.model.domain.User;
import edu.zut.summer.model.request.LoginUserRequest;
import edu.zut.summer.model.request.RegisterUserRequest;
import edu.zut.summer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RequestMapping("/rest/users")
@CrossOrigin
@Controller
public class UserRestApi {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", produces = "application/json", method = RequestMethod.GET )
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        log.info("username++++++"+username);
        log.info("passworrd++++++"+password);
        LoginUserRequest login = new LoginUserRequest(username,password);
        log.info("log++++++>: " + login.toString());
        User user  =userService.loginUser(login);
        log.info("user+++++>: "+ user);
        Map<String, Object> map = new HashMap<>();
        map.put("success",user != null);
        map.put("user",user);
        log.info("return map ++++"+map.toString());
        return map;
    }

    @RequestMapping(value = "/register", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> addUser(@RequestParam("username") String username, @RequestParam("password") String password) {
        Map<String,Object> map = new HashMap<>();
        if(userService.checkUserExist(username)){
            map.put("success",false);
            map.put("message","用户名已经被注册！");
            return map;
        }
        map.put("success",userService.registerUser(new RegisterUserRequest(username,password)));
        return map;
    }

    //冷启动问题
    @RequestMapping(value = "/pref", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> addPrefGenres(@RequestParam("username") String username, @RequestParam("genres") String genres) {
        User user = userService.findByUsername(username);
        user.getPrefGenres().addAll(Arrays.asList(genres.split(",")));
        user.setFirst(false);
        Map<String,Object> map = new HashMap<>();
        map.put("success",userService.updateUser(user));
        return map;
    }

    @RequestMapping(value = "/info", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getInfo(@RequestParam("username") String username) {
        Map<String,Object> map = new HashMap<>();
        map.put("new", userService.checkNew(username));
        return map;
    }
}
